#!/usr/bin/python3

import asynchat
import asyncore
import logging
import socket
import sys

class Client(asynchat.async_chat):
    '''Client for testing kiwi. Use it to issue commands'''

    def __init__(self, host, port):
        self.logger = logging.getLogger('Client')
        super().__init__()        
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.logger.info('connecting to %s', (host, port))
        self.connect((host, int(port)))
        return

    def handle_connect(self):
        self.logger.info('connected')
        self.waitForUserInput()

    def waitForUserInput(self):
        print('>>>', end='')
        command = input()
        if command == 'quit':
            self.close_when_done()
            return
        data = command.encode('ascii')
        self.push('JSON {:d}\r\n'.format(len(data)).encode('ascii'))
        self.push(data)
        self.buffer = []
        self.set_terminator(b'\r\n')
        self.process_data = self._process_length
        
    def found_terminator(self):
        self.logger.debug('found terminator')
        self.process_data()

    def _process_length(self):
        json, length = ''.join(self.buffer).strip().split(' ')
        length = int(length)
        self.logger.debug('json msg length: {}'.format(length))
        self.set_terminator(length)
        self.process_data = self._process_json
        self.buffer = []

    def collect_incoming_data(self, data):
        self.buffer.append(data.decode('ascii'))

    def _process_json(self):
        print(''.join(self.buffer).strip())
        self.waitForUserInput()
        

    def run(self):
        asyncore.loop()

if __name__ == '__main__':
    logging.basicConfig(level = logging.INFO)
    client = Client(sys.argv[1], sys.argv[2])
    client.run()
    
